threading 共享数据的保护
import threading
import time,random
class Counter:
''''''
def __init__(self):
self.lock = threading.Lock()
self.value = 0
def increment(self):
self.lock.acquire()
self.value = value = self.value + 1
self.lock.release()
return value
counter = Counter()
class Worker(threading.Thread):
''''''
def run(self):
for i in xrange(4):
value = counter.increment()
time.sleep(random.randint(10,100)/1000.0)
print self.getName(),'--task',i,'finished',value
for i in xrange(3):
Worker().start()
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Thread-2 --task 0 finished 2
Thread-1 --task 0 finished 1
Thread-3 --task 0 finished 3
Thread-2 --task 1 finished 4
Thread-1 --task 1 finished 5
Thread-2 --task 2 finished 7
Thread-1 --task 2 finished 8
Thread-1 --task 3 finished 10
Thread-2 --task 3 finished 9
Thread-3 --task 1 finished 6
Thread-3 --task 2 finished 11
Thread-3 --task 3 finished 12